package com.mini.cn.goods.action;

import com.alibaba.fastjson.JSONObject;
import com.mini.cn.goods.exception.MiniGoodsException;
import com.mini.cn.goods.po.*;
import com.mini.cn.goods.po.dto.GroupDesDto;
import com.mini.cn.goods.util.ErrorMsg;
import com.mini.cn.goods.util.TimeUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: fly
 * Date: 2022/11/19
 * Time: 17:55
 */
public class GroupSaleAction extends BaseAction {

    public GroupSaleAction(int balance, UserInfo userInfo, Object o) {
        super(balance, userInfo, o);
    }

    @Override
    public boolean filterAction(Action action, Object O) {
        String condition = action.getcCondition();
        int appid = action.getcAppid();
        GroupSaleActionDes groupDes = JSONObject.parseObject(condition, GroupSaleActionDes.class);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        final String time = sdf.format(new Date());
        String bt = groupDes.getGroupBeginTime();
        String et = groupDes.getGroupEndTime();
        long bc = TimeUtil.compareTimeByHM(time, bt);
        long ec = TimeUtil.compareTimeByHM(time, et);
        //判断是否在接龙时间
        if (null == O) {
            if (bc < 0 || ec > 0) {
                throw new MiniGoodsException(String.valueOf(ErrorMsg.STATUS_GROUPTIMEOUT_ERROR),
                        ErrorMsg.MSG_GROUPTIMEOUT_ERROR);
            }
            return false;
        }
        GroupDesDto desDto = (GroupDesDto) O;
        if (bc < 0 || ec > 0) {
            desDto.setEnd(true);
        }
        //配置
        List<GroupSaleTimeGoods> list = groupDes.getGoodsList();
        desDto.setBeginTime(groupDes.getGroupBeginTime());
        desDto.setEndTime(groupDes.getGroupEndTime());
        desDto.setTackAddress(groupDes.getGroupAddress());
        desDto.setTackTime(groupDes.getGroupTackTime());
        //所有的商品
        List<GoodsInfo> goodsInfos = desDto.getGoods();
        List<GoodsInfo> tempGoodsInfo = new ArrayList<>();
        for (GroupSaleTimeGoods groupSaleTimeGoods : list) {
            String gid = groupSaleTimeGoods.getGoodsId();
            //查找GoodInfo
            GoodsInfo goodsInfo = findGoodsInfoByGid(gid, goodsInfos);
            if (null == goodsInfo) {
                continue;
            }
            goodsInfo.setcPrice(groupSaleTimeGoods.getDisPrice());
            tempGoodsInfo.add(goodsInfo);
        }
        goodsInfos.clear();
        goodsInfos.addAll(tempGoodsInfo);
        return false;
    }

    private GoodsInfo findGoodsInfoByGid(String gid, List<GoodsInfo> goodsInfos) {
        for (GoodsInfo goodsInfo : goodsInfos) {
            String goodId = goodsInfo.getcGoodsid();
            if (goodId.equals(gid)) {
                return goodsInfo;
            }
        }
        return null;
    }
}
